package com.pengshun.modules.aliyun;

import com.aliyun.oss.ClientException;
import com.aliyun.push20160801.Client;
import com.aliyun.push20160801.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.aliyuncs.utils.ParameterHelper;
import com.google.gson.Gson;
import com.pengshun.config.oss.OSSClientConstants;

import java.rmi.ServerException;
import java.util.Date;

/**
 * @author luoligang
 * @create 2021/3/17
 */
public class OosPush {

    private static Long APPKEY = (long) 333393047;
    private static String accessKeyId = OSSClientConstants.ACCESS_KEY_ID;
    private static String accessKeySecret = OSSClientConstants.ACCESS_KEY_SECRET;

    public static void main(String[] args) {
        push("ceshAAi","大1家好呀","TAG","binmeitongfourtag");
    }
    /**
     * 消息推送
     *
     * @param
     */
    public static void push(String title, String body, String target, String targetValue) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = OSSClientConstants.ENDPOINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        PushRequest request = new PushRequest();
        request.setRegionId("cn-hangzhou");
        request.setAppKey(APPKEY);
        request.setPushType("NOTICE");
        request.setDeviceType("ALL");//iOS：iOS设备     ANDROID：Android设备     ALL：全部类型设备
        request.setTarget(target);//DEVICE：根据设备推送       //ACCOUNT：根据账号推送   //ALIAS：根据别名推送  TAG：根据标签推送  ALL：推送给全部设备
        request.setTargetValue(targetValue);
        request.setTitle(title);
        request.setBody(body);
        request.setAndroidNotifyType("BOTH");//通知的提醒方式。VIBRATE：震动、SOUND：声音、BOTH：声音和震动、NONE：静音。
        request.setAndroidNotificationChannel("1");// 指定notificaitonchannel id。
        // 推送配置
        request.setPushType("NOTICE"); // 0:表示消息(MESSAGE), 1:表示通知NOTICE
        //request.setSummary("PushRequest summary"); // 通知的摘要
        //request.setAndroidNotificationBarType(2);//设置的通知样式ID，通知栏自定义样式范围0-100
        // 推送配置: Android
        request.setAndroidOpenType("APPLICATION");   // 点击通知后动作,1:打开应用 2: 打开应用Activity 3:打开 url  点击通知后动作：APPLICATION     打开应用：ACTIVITY      打开URL：URL       无打开动作：NONE
        //request.setAndroidOpenUrl();
        //request.setAndroidActivity("com.pengshun.bmt.activity.message.MessageActivity");
        // 额外参数
        //request.setAndroidExtParameters("{\"_NOTIFICATION_BAR_STYLE_\":\"2\"}");
        request.setAndroidPopupActivity("1"); // 设置辅助弹窗打开Activity，填写Activity类名，需包名+类名
        request.setAndroidPopupTitle(title);  // 设置辅助弹窗通知标题
        request.setAndroidPopupBody(body); // 设置辅助弹窗通知内容
        // 72小时后消息失效, 不会再发送
        String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 72 * 3600 * 1000));
        request.setExpireTime(expireTime);
        // 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
        request.setStoreOffline(true);
        //推送消息类型时，设置true，设备离线时会自动把消息转成辅助通道的通知
        request.setAndroidRemind(true);

        try {
            PushResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrorCode());
            System.out.println("ErrMsg:" + e.getErrorMessage());
            System.out.println("RequestId:" + e.getRequestId());
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }

    }

    /**
     * 绑定别名
     *
     * @return
     */
    public static void bindAlias(String deviceId, Long userId) throws Exception {
        String aliasName = "binmeitongAlias" + userId;
        //系统规定参数。取值：BindAlias。
        Client client = OosPush.createClient();
        //查询
        QueryAliasesRequest queryAliasesRequest = new QueryAliasesRequest()
                .setAppKey(APPKEY)
                .setDeviceId(deviceId);
        QueryAliasesResponse response = client.queryAliases(queryAliasesRequest);
        if (response != null) {
            QueryAliasesResponseBody.QueryAliasesResponseBodyAliasInfos aliasInfo = response.getBody().aliasInfos;
            for (QueryAliasesResponseBody.QueryAliasesResponseBodyAliasInfosAliasInfo qa : aliasInfo.aliasInfo) {
                //解绑
                UnbindAliasRequest unbindAliasRequest = new UnbindAliasRequest()
                        .setAppKey(APPKEY)
                        .setDeviceId(deviceId)
                        .setAliasName(qa.aliasName);
                // 复制代码运行请自行打印 API 的返回值
                client.unbindAlias(unbindAliasRequest);
            }

        }
        BindAliasRequest bindAliasRequest = new BindAliasRequest()
                .setAppKey(APPKEY)
                .setDeviceId(deviceId)
                .setAliasName(aliasName);
        // 复制代码运行请自行打印 API 的返回值
        client.bindAlias(bindAliasRequest);
    }

    /**
     * 绑定TAG
     *
     * @return
     */
    public static void bindTag(Long userId, String tagName) throws Exception {
        Client client = OosPush.createClient();
        //系统规定参数。取值：BindAlias。
        String clientKey = "binmeitongAlias" + userId;
        //查询tag
        QueryTagsRequest queryTagsRequest = new QueryTagsRequest()
                .setAppKey(APPKEY)
                .setClientKey(clientKey)
                .setKeyType("ALIAS");
        // 复制代码运行请自行打印 API 的返回值
        QueryTagsResponse response = client.queryTags(queryTagsRequest);
        if (response != null) {
            QueryTagsResponseBody.QueryTagsResponseBodyTagInfos tagInfos = response.getBody().getTagInfos();
            for (QueryTagsResponseBody.QueryTagsResponseBodyTagInfosTagInfo qt : tagInfos.tagInfo) {
                //解绑
                UnbindTagRequest unbindTagRequest = new UnbindTagRequest()
                        .setAppKey(APPKEY)
                        .setClientKey(clientKey)
                        .setKeyType("ALIAS")
                        .setTagName(qt.getTagName());
                // 复制代码运行请自行打印 API 的返回值
                client.unbindTag(unbindTagRequest);
            }

        }
        //绑定
        BindTagRequest bindTagRequest = new BindTagRequest()
                .setAppKey(APPKEY)
                .setClientKey(clientKey)
                .setKeyType("ALIAS")
                .setTagName(tagName);
        // 复制代码运行请自行打印 API 的返回值com.aliyuncs.push.model.v20160801
        client.bindTag(bindTagRequest);
    }

    /**
     * 解除绑定tag
     *
     * @param userId
     * @param tagName
     * @throws Exception
     */
    public static void unbindTag(Long userId, String tagName) throws Exception {
        String clientKey = "binmeitongAlias" + userId;
        Client client = OosPush.createClient();
        UnbindTagRequest unbindTagRequest = new UnbindTagRequest()
                .setAppKey(APPKEY)
                .setClientKey(clientKey)
                .setKeyType("ALIAS")
                .setTagName("tagName");
        // 复制代码运行请自行打印 API 的返回值
        client.unbindTag(unbindTagRequest);
    }

    public static com.aliyun.push20160801.Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "cloudpush.aliyuncs.com";
        return new com.aliyun.push20160801.Client(config);
    }

}
